var num=0;
var int;
var hard=0.2;
var add_hand=1.1;
var score=0;

function debug(){
}

window.onload=function(){
	getClass("p_start")[0].onclick=startGame;
	getClass("p_restart")[0].onclick=restart;
	debug();
}

function getClass(className){
	return document.getElementsByClassName(className);
}


function startGame(){
	getClass("page1")[0].style.display="none";
	getClass("page2")[0].style.display="inline-block";
	init();
}

function restart(){
	getClass("page3")[0].style.display="none";
	getClass("page1")[0].style.display="inline-block";
}

function gameend(){
	clearInterval(int);
	getClass("result")[0].innerHTML=score;
	getClass("page2")[0].style.display="none";
	getClass("page3")[0].style.display="inline-block";
}

function init(){
	var hands=getClass("hand");
	for(var i=0;i<hands.length;i++){
		var hand=hands[i];
		hand.parentNode.removeChild(hand);
	}
	score=0;
	int=setInterval(circle,200);
}

function circle(){
	//美女图片循环
	if(num>7) num=0;
	getClass("img")[0].setAttribute("src","imgs/touchme"+num+".png");
	num++;

	var build=Math.floor(add_hand);
	for(var i=0;i<build;i++){
		addHand();
	}
	add_hand-=build;
	add_hand+=hard;

	//碰撞检测
	var hands=getClass("hand");
	for(var i=0;i<hands.length;i++){
		var hand=hands[i];
		if(touch(hand)){
			//摸到了
			gameend();
			return;
		}
	}
}

function touch(hand){
	var top=hand.style.top;
	var left=hand.style.left;
	var top_num=Number(top.substr(0,top.indexOf("%")));
	var left_num=Number(left.substr(0,left.indexOf("%")));
	if(top_num<=40&&top_num>=34&&left_num<=51&&left_num>=34){
		//摸到了，结束
		return true;
	}
	if(top_num<34){
		top_num++;
	}
	else if(top_num>40){
		top_num--;
	}
	hand.style.top=top_num+"%";
	
	if(left_num<34){
		left_num++;
	}
	else if(left_num>51){
		left_num--;
	}
	hand.style.left=left_num+"%";
	return false;
}

function addHand(){
	var hand=document.createElement("img");
	hand.setAttribute("src","imgs/hand.png");
	var arrs=getTwoRan();
	hand.style.top=arrs[0]+"%";
	hand.style.left=arrs[1]+"%";
	hand.className="hand";
	hand.onclick=handClick;
	getClass("dv_wp")[0].appendChild(hand);
}

function getTwoRan(){
	var arrs=[2];
	var ran=Math.random();
	var ran1=Math.floor(Math.random()*100);
	var ran2=Math.floor((Math.random()<0.5)?-10:110);
	if(ran<0.5){
		arrs[0]=ran1;
		arrs[1]=ran2;
	}
	else{
		arrs[0]= ran2;
		arrs[1]=ran1;
	}
	return arrs;
}

function handClick(){
	this.parentNode.removeChild(this);
	score+=1;
	getClass("label")[0].innerHTML=score;
}